<?php
/**
 * 广告管理
 * Author: xx.com
 * Date: 2015-09-21
 */

namespace Admin\Controller;

class AdController extends BaseController{
    public function ad(){       
        $act = I('GET.act','add');
        $ad_id = I('GET.ad_id');
        $ad_info = array();
        if($ad_id){
            $ad_info = D('ad')->where('ad_id='.$ad_id)->find();
            $ad_info['start_time'] = date('Y-m-d',$ad_info['start_time']);
            $ad_info['end_time'] = date('Y-m-d',$ad_info['end_time']);
            $ad_info_extent = D('ad_extent')->where('ad_id='.$ad_id)->find();
            if ($ad_info_extent)
            {
                $ad_info_extent['answer'] = unserialize( $ad_info_extent['answer'] ) ? unserialize( $ad_info_extent['answer'] ) : '';
                $ad_info = array_merge($ad_info_extent,$ad_info);
            }
        }
        if($act == 'add')          
           $ad_info['pid'] = $_GET['pid'];                
        $position = D('ad_position')->where('1=1')->select();
        // p($ad_info);
        $this->assign('info',$ad_info);
        $this->assign('act',$act);
        $this->assign('position',$position);
        $this->display();
    }
    
    public function adList(){
        
        delFile(RUNTIME_PATH.'Html'); // 先清除缓存, 否则不好预览
            
        $Ad =  M('ad'); 
        $where = "1=1";
        if(I('pid')){
        	$where = "pid=".I('pid');
        	$this->assign('pid',I('pid'));
        }
        $keywords = I('keywords',false);
        if($keywords){
        	$where = "ad_name like '%$keywords%'";
        }
        $count = $Ad->where($where)->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数
        // pid desc
        $res = $Ad->where($where)->order('orderby asc')->limit($Page->firstRow.','.$Page->listRows)->select();
        
        if($res){
            $media = array('图片','flash');
            $ad_extend = M("ad_extent");
        	foreach ($res as $k => &$val){
                $val['media_type'] = $media[$val['media_type']];
                $val['extend'] = $ad_extend->where([
                    "ad_id" => $val['ad_id']
                ])->find();
        	}
        }
        // p($res);die;
        $ad_position_list = M('AdPosition')->getField("position_id,position_name,is_open");                     
        $this->assign('ad_position_list',$ad_position_list);//广告位 
        // p($list);
        $show = $Page->show();// 分页显示输出
        $this->assign('list',$res);// 赋值数据集
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }
    
    public function position(){
        $act = I('GET.act','add');
        $position_id = I('GET.position_id');
        $info = array();
        if($position_id){
            $info = D('ad_position')->where('position_id='.$position_id)->find();
            $this->assign('info',$info);
        }
        $this->assign('act',$act);
        $this->display();
    }
    
    public function positionList(){
        $Position =  M('ad_position');
        $count = $Position->where('1=1')->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数
        $list = $Position->order('position_id DESC')->limit($Page->firstRow.','.$Page->listRows)->select();
        
        $this->assign('list',$list);// 赋值数据集                
        $show = $Page->show();// 分页显示输出
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }
    
    public function adHandle(){
    	$data = I('post.');
    	$data['start_time'] = strtotime($data['begin']);
    	$data['end_time'] = strtotime($data['end']);
        $data['media_type'] = I('media_type');

        if( !$data['is_join_rebate'] )
        {
            unset($data['answer']);
        }else{
            if(empty($data['answer']) || empty($data['answer']['list']) )
                $this->error("答案设置错误");

            if( count($data['answer']['list']) < 2 )
                $this->error("答案不能只设置一个");

            if( !isset($data['answer']['list'][$data['answer']['selected']]) || empty( $data['answer']['list'][$data['answer']['selected']] ) )
                $this->error("选择的答案不能为空");

            $data['answer'] = serialize($data['answer']);
        }

    	if($data['act'] == 'add'){
    		$r = D('ad')->add($data);
    		if ($r){
                $post['create_time'] = time();
                $post['ad_id'] = $r;
                $post['is_join_rebate'] = $data['is_join_rebate'] ? 1:0;
                $post['rebate'] = $data['is_join_rebate'] ? $data['rebate'] : 0;
                $post['question'] = $data['is_join_rebate'] ? $data['question'] : '';
                $post['answer'] = $data['is_join_rebate'] ? $data['answer'] : '';
                D('ad_extent')->add($post);
            }
    	}
    	if($data['act'] == 'edit'){
            // var_dump($data);die;
            $where = ['ad_id' => $data['ad_id']];
            $model = D('ad');
   	        try{
                $r = $model->where($where)->save($data);

                if( D('ad_extent')->where($where)->find() )
                {
                    D('ad_extent')->where($where)->save($data);
                }else{
                    $post['create_time'] = time();
                    $post['ad_id'] = $data['ad_id'];
                    $post['is_join_rebate'] = $data['is_join_rebate'] ? 1:0;
                    $post['rebate'] = $data['is_join_rebate'] ? $data['rebate'] : 0;
                    $post['question'] = $data['is_join_rebate'] ? $data['question'] : '';
                    $post['answer'] = $data['is_join_rebate'] ? $data['answer'] : '';
                    D('ad_extent')->add($post);
                }
            }catch (\Exception $e){
                $this->error($e->getMessage(),$referurl);   
            }
    	}
    	
    	if($data['act'] == 'del'){
    		$r = D('ad')->where('ad_id='.$data['del_id'])->delete();
            D('ad_extent')->where('ad_id='.$data['del_id'])->delete();
    		if($r) exit(json_encode(1));
    	}
    	$referurl = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : U('Admin/Ad/adList');
        // 不管是添加还是修改广告 都清除一下缓存
        delFile(RUNTIME_PATH.'Html'); // 先清除缓存, 否则不好预览
        
    	if($r === false){
            $this->error("操作失败",$referurl);
    	}else{
            $this->success("操作成功",U('Admin/Ad/adList'));
    	}
    }

    
    public function positionHandle(){
        $data = I('post.');
        if($data['act'] == 'add'){
            $r = M('ad_position')->add($data);
        }
        
        if($data['act'] == 'edit'){
        	$r = M('ad_position')->where('position_id='.$data['position_id'])->save($data);
        }
        
        if($data['act'] == 'del'){
        	if(M('ad')->where('pid='.$data['position_id'])->count()>0){
        		$this->error("此广告位下还有广告，请先清除",U('Admin/Ad/positionList'));
        	}else{
        		$r = M('ad_position')->where('position_id='.$data['position_id'])->delete();
        		if($r) exit(json_encode(1));
        	}
        }
        $referurl = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : U('Admin/Ad/positionList');
        if($r){
        	$this->success("操作成功",$referurl);
        }else{
        	$this->error("操作失败",$referurl);
        }
    }
    
    public function changeAdField(){
    	$data[$_REQUEST['field']] = I('GET.value');
    	$data['ad_id'] = I('GET.ad_id');
    	M('ad')->save($data); // 根据条件保存修改的数据
    }


    
    //广告统计
    //2018-7-27
    public function ad_statistics(){
        if(IS_POST){
            //获取所有广告的全部点击量
            $data=M('ad_click')->field("MONTH(create_time) as create_time,COUNT(*) as count")->group('MONTH(create_time)')->select();
            foreach($data as $k=>&$v){
                $v['create_time']=$v['create_time'].'月';
            }
            //按月统计
            $create_time=array_column($data,'create_time');
            $count=array_column($data,'count');
            $option = [
                'title'=> ['text'=>'点击量按月统计'],
                'tooltip'=>['trigger'=> 'axis'],
                'legend'=>['data'=>['广告月点击量']],
                'grid'=> ['left'=> '3%', 'right'=> '4%', 'bottom'=> '3%', 'containLabel'=> true],
                'toolbox'=> ['feature'=> ['saveAsImage'=> []]],
                'xAxis'=> ['type'=>'category', 'boundaryGap'=> false, 'data'=> $create_time],
                'yAxis'=> ['type'=> 'value'],
                'series'=> [['name'=>'点击量', 'type'=>'line', 'stack'=> '总量', 'data'=>$count]]
            ];
            //按照周统计
            $data_week=M('ad_click')->field("WEEKDAY(create_time) create_time,COUNT(*) as count")->group("WEEKDAY(create_time)")->select();
            foreach($data_week as $k=>&$v){
                if($v['create_time']==0){
                    $v['create_time']="每周一";
                }else if($v['create_time']==1){
                    $v['create_time']="每周二";
                }else if($v['create_time']==2){
                    $v['create_time']="每周三";
                }else if($v['create_time']==3){
                    $v['create_time']="每周四";
                }else if($v['create_time']==4){
                    $v['create_time']="每周五";
                }else if($v['create_time']==5){
                    $v['create_time']="每周六";
                }else if($v['create_time']==6){
                    $v['create_time']="每周日";
                }


            }
            $create_time_week=array_column($data_week,'create_time');
            $count_week=array_column($data_week,'count');
            $option_week = [
                'title'=> ['text'=>'点击量按每周统计'],
                'tooltip'=>['trigger'=> 'axis'],
                'legend'=>['data'=>['广告天点击量']],
                'grid'=> ['left'=> '3%', 'right'=> '4%', 'bottom'=> '3%', 'containLabel'=> true],
                'toolbox'=> ['feature'=> ['saveAsImage'=> []]],
                'xAxis'=> ['type'=>'category', 'boundaryGap'=> false, 'data'=> $create_time_week],
                'yAxis'=> ['type'=> 'value'],
                'series'=> [['name'=>'点击量', 'type'=>'line', 'stack'=> '总量', 'data'=>$count_week]]
            ];

            //按照天统计
            $data_day=M('ad_click')->field("DATE_FORMAT(create_time,'%Y-%m-%d') as create_time,COUNT(*) as count")->group("DATE_FORMAT(create_time,'%Y-%m-%d')")->select();
            $create_time_day=array_column($data_day,'create_time');
            $count_day=array_column($data_day,'count');
            $option_day = [
                'title'=> ['text'=>'点击量按天统计'],
                'tooltip'=>['trigger'=> 'axis'],
                'legend'=>['data'=>['广告天点击量']],
                'grid'=> ['left'=> '3%', 'right'=> '4%', 'bottom'=> '3%', 'containLabel'=> true],
                'toolbox'=> ['feature'=> ['saveAsImage'=> []]],
                'xAxis'=> ['type'=>'category', 'boundaryGap'=> false, 'data'=> $create_time_day],
                'yAxis'=> ['type'=> 'value'],
                'series'=> [['name'=>'点击量', 'type'=>'line', 'stack'=> '总量', 'data'=>$count_day]]
            ];
            exit(json_encode(['monty'=>$option,'day'=>$option_day,'week'=>$option_week]));
        }else{
            $this->display();
        }

    }

    //通过月统计
    public function ad_statistics_monty(){
        $time=I('time');
        $date_time=explode('-',$time);
        $start_time=$date_time[0].'-'.$date_time[1].'-'.$date_time[2];
        $end_time=$date_time[3].'-'.$date_time[4].'-'.$date_time[5];
        //获取所有广告的全部点击量
        $data=M('ad_click')->field("MONTH(create_time) as create_time,COUNT(*) as count")->where("create_time >= '$start_time' and create_time <='$end_time'")->group('MONTH(create_time)')->select();
        foreach($data as $k=>&$v){
            $v['create_time']=$v['create_time'].'月';
        }
        //按月统计
        $create_time=array_column($data,'create_time');
        $count=array_column($data,'count');
        $option = [
            'title'=> ['text'=>'点击量按月统计'],
            'tooltip'=>['trigger'=> 'axis'],
            'legend'=>['data'=>['广告月点击量']],
            'grid'=> ['left'=> '3%', 'right'=> '4%', 'bottom'=> '3%', 'containLabel'=> true],
            'toolbox'=> ['feature'=> ['saveAsImage'=> []]],
            'xAxis'=> ['type'=>'category', 'boundaryGap'=> false, 'data'=> $create_time],
            'yAxis'=> ['type'=> 'value'],
            'series'=> [['name'=>'点击量', 'type'=>'line', 'stack'=> '总量', 'data'=>$count]]
        ];
        exit(json_encode($option));
    }

    public function ad_statistics_week(){
        $time=I('time');
        $date_time=explode('-',$time);
        $start_time=$date_time[0].'-'.$date_time[1].'-'.$date_time[2];
        $end_time=$date_time[3].'-'.$date_time[4].'-'.$date_time[5];
        //获取所有广告的全部点击量
        $data_week=M('ad_click')->field("WEEKDAY(create_time) create_time,COUNT(*) as count")->where("create_time >= '$start_time' and create_time <='$end_time'")->group("WEEKDAY(create_time)")->select();
        foreach($data_week as $k=>&$v){
            if($v['create_time']==0){
                $v['create_time']="每周一";
            }else if($v['create_time']==1){
                $v['create_time']="每周二";
            }else if($v['create_time']==2){
                $v['create_time']="每周三";
            }else if($v['create_time']==3){
                $v['create_time']="每周四";
            }else if($v['create_time']==4){
                $v['create_time']="每周五";
            }else if($v['create_time']==5){
                $v['create_time']="每周六";
            }else if($v['create_time']==6){
                $v['create_time']="每周日";
            }


        }
        $create_time_week=array_column($data_week,'create_time');
        $count_week=array_column($data_week,'count');
        $option_week = [
            'title'=> ['text'=>'点击量按每周统计'],
            'tooltip'=>['trigger'=> 'axis'],
            'legend'=>['data'=>['广告天点击量']],
            'grid'=> ['left'=> '3%', 'right'=> '4%', 'bottom'=> '3%', 'containLabel'=> true],
            'toolbox'=> ['feature'=> ['saveAsImage'=> []]],
            'xAxis'=> ['type'=>'category', 'boundaryGap'=> false, 'data'=> $create_time_week],
            'yAxis'=> ['type'=> 'value'],
            'series'=> [['name'=>'点击量', 'type'=>'line', 'stack'=> '总量', 'data'=>$count_week]]
        ];
        exit(json_encode($option_week));
    }

    //点击量按天统计
    public function ad_statistics_day(){
        $time=I('time');
        $date_time=explode('-',$time);
        $start_time=$date_time[0].'-'.$date_time[1].'-'.$date_time[2];
        $end_time=$date_time[3].'-'.$date_time[4].'-'.$date_time[5];
        //按照天统计
        $data_day=M('ad_click')->field("DATE_FORMAT(create_time,'%Y-%m-%d') as create_time,COUNT(*) as count")->where("create_time >= '$start_time' and create_time <='$end_time'")->group("DATE_FORMAT(create_time,'%Y-%m-%d')")->select();
        $create_time_day=array_column($data_day,'create_time');
        $count_day=array_column($data_day,'count');
        $option_day = [
            'title'=> ['text'=>'点击量按天统计'],
            'tooltip'=>['trigger'=> 'axis'],
            'legend'=>['data'=>['广告天点击量']],
            'grid'=> ['left'=> '3%', 'right'=> '4%', 'bottom'=> '3%', 'containLabel'=> true],
            'toolbox'=> ['feature'=> ['saveAsImage'=> []]],
            'xAxis'=> ['type'=>'category', 'boundaryGap'=> false, 'data'=> $create_time_day],
            'yAxis'=> ['type'=> 'value'],
            'series'=> [['name'=>'点击量', 'type'=>'line', 'stack'=> '总量', 'data'=>$count_day]]
        ];
        exit(json_encode($option_day));
    }


    //统计新老用户注册饼图
    public function user_statistics(){
        $time=strtotime(date("Y-m-d"),time());
        //统计当天注册的人数
        $same_day=M('users')->where("reg_time >$time")->count();

        //统计之前的注册的所有人数
        $before=M('users')->where("reg_time < $time")->count();

        $option = [
            'title' => ['text'=> '鲜美特用户注册统计', 'subtext'=> '新用户老用户对比', 'x'=>'center'],
            'tooltip' => ['trigger'=> 'item', 'formatter'=> "{a} <br/>{b} : {c} ({d}%)"],
            'legend'=> ['orient'=> 'vertical', 'left'=> 'left', 'data'=> ['新用户注册','老用户注册']],
            'series'=> [[
                'name'=> '注册比例',
                'type'=> 'pie',
                'radius' => '55%',
                'center'=> ['50%', '60%'],
                'data'=>[
                    ['value'=>$same_day, 'name'=>'新用户注册'],
                    ['value'=>$before, 'name'=>'老用户注册'],
                ],
                'itemStyle'=> [
                    'emphasis'=> ['shadowBlur'=> 10, 'shadowOffsetX'=> 0, 'shadowColor'=> 'rgba(0, 0, 0, 0.5)']
                ]
            ]
            ]
        ];
        exit(json_encode($option));

    }


}
